﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using mshtml;
using System.IO;
using HtmlAgilityPack;
using Web.Dal;

namespace ZFCG_Localized
{
    public partial class Frm_Main_ZB : Form
    {
        /// <summary>
        /// 用于下载图片的WebClient类
        /// </summary>
        private WebClient aWebClient = new WebClient();

        private int count = 1; 

        private string aBaseUrl = "http://shaoguan.gdgpo.com";

        private string aFirstUrl = "http://shaoguan.gdgpo.com/gdgpmsPortal/jsp/executeOrganArticleCol.jsp?webId=4028889705bebb510105becc5dbf0008&nodeCode=0005&ismultilist=1";

        private bool aIsStartAnalyze = false;

        private WebBrowser aWebBrowser = new WebBrowser();

        public Frm_Main_ZB()
        {
            InitializeComponent();
            this.comb_type.SelectedIndex = 0;
            aWebBrowser.DocumentCompleted+=new WebBrowserDocumentCompletedEventHandler(aWebBrowser_DocumentCompleted);
            this.lab_version.Text += System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }

        private void aWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (aIsStartAnalyze == false)
            {
                return;
            }
            if (aWebBrowser.ReadyState < WebBrowserReadyState.Complete)
            {
                return; //保证每个页面只执行以下代码一次
            }
            
            DomOpert();

            NextPage();
        }

        private void NextPage()
        {
            if (rbtn_pagend.Checked)
            {
                if (this.count >= nud_maxpage.Value)
                {
                    btn_Start_Click(null, null);
                    return;
                }
            }

            IHTMLDocument2 doc = aWebBrowser.Document.DomDocument as IHTMLDocument2;
            IHTMLWindow2 win = doc.parentWindow;

            win.execScript(string.Format("GoPage({0});", ++count), "javascript");
        }

        private void DomOpert()
        {
            lab_currentpage.Text = String.Format("第{0}页", count);

            #region 使用HtmlAgilityPack解析Html

            HtmlAgilityPack.HtmlDocument iHtmlDoc = new HtmlAgilityPack.HtmlDocument();
            iHtmlDoc.Load(aWebBrowser.DocumentStream);
            //<table width="87%" border="0" align="center" cellpadding="0" cellspacing="0">
            HtmlAgilityPack.HtmlNode itableNode = iHtmlDoc.DocumentNode.SelectSingleNode("//table[@width='87%']");
            HtmlAgilityPack.HtmlNodeCollection itrs = itableNode.SelectNodes("./tr[@valign='top']");
            if ((itrs == null) || itrs.Count <= 0)
            {
                return;
            }
            List<ZFCGObjClass> iZFCGObjList = new List<ZFCGObjClass>();
            foreach (HtmlNode itr in itrs)
            {
                HtmlNodeCollection ispans = itr.SelectNodes(".//span");
                if ((ispans == null) || (ispans.Count <= 0))
                {
                    continue;
                }
                ZFCGObjClass iZFCGObj = new ZFCGObjClass();
                HtmlNode ispan = ispans[0];
                if (check_isfite.Checked)
                {
                    string iFilterStr = txt_fitestr.Text;
                    if (ispan.InnerText.Contains(iFilterStr) == false)
                    {
                        continue;
                    }
                }
                iZFCGObj.title = ispan.InnerText;
                string ionclick_str = ispan.GetAttributeValue("onclick", "");
                string iid = ionclick_str.Substring(ionclick_str.IndexOf("'") + 1, 32);
                iZFCGObj.url = string.Format("{0}/gdgpmsPortal/jsp/article_content.jsp?articleId={1}", aBaseUrl, iid);

                ispan = ispans[1];
                iZFCGObj.datetime = DateTime.Parse(ispan.InnerText.Replace("(", "").Replace(")", ""));
                iZFCGObj.datetime_str = iZFCGObj.datetime.ToString("yyyy-MM-dd");

                ispan = ispans[2];
                iZFCGObj.area = ispan.InnerText;

                if (this.rbtn_auto.Checked)
                {
                    string iselebasestr = "select zid from zfcg where title='{0}' and datetime='{1}'";
                    using (DbDataReader iselereader =
                        C_SqlOperate.ExecCommStr_Reader(
                        string.Format(iselebasestr, iZFCGObj.title, iZFCGObj.datetime_str)))
                    {
                        if (iselereader.HasRows)
                        {
                            btn_Start_Click(null, null);
                            break;
                        }
                    }
                }

                iZFCGObjList.Add(iZFCGObj);
            }
            ShowDataList(iZFCGObjList);

            #endregion


            /*
            #region 使用C#自带的Html类解析Html
            HtmlElementCollection ispans = aWebBrowser.Document.GetElementsByTagName("span");

            if (ispans == null)
            {
                return;
            }

            for (Int32 i = 0; i < ispans.Count; i++)
            {
                HtmlElement ispan = ispans[i];
                HTMLSpanElement ispan_obj = (HTMLSpanElement)ispan.DomElement;
                String ispan_class = ispan_obj.className;
                if ((ispan_class == null) || (ispan_class == "") || (ispan_class != "cglist"))
                {
                    continue;
                }

                listBox1.Items.Add(ispan.InnerText);
                listBox1.SelectedItem = listBox1.Items[listBox1.Items.Count - 1];
                Application.DoEvents();

                //String idocurl = "";
                //String idocfilepath = aDFilePath + td_a.InnerText + ".doc";
                //String ihtmlfilepath = aDFilePath + td_a.InnerText + ".htm";
                //String itd_a_href_doc = "";
                //if (itd_a_href.LastIndexOf(".") > 23)
                //{
                //    itd_a_href_doc = itd_a_href.Substring(23, itd_a_href.LastIndexOf(".") - 23);
                //}
                //else
                //{
                //    itd_a_href_doc = itd_a_href.Substring(23);
                //}
                //idocurl = String.Format(aFileUrl1, itd_a_href_doc);
                //if (!DownloadFile(idocurl, idocfilepath))
                //{
                //    if (!DownloadFile(itd_a_href, ihtmlfilepath))
                //    {
                //        listBox1.Items.Add(String.Format("{0} {1} DOC和HTML文档下载失败！", i + 1, td_a.InnerText));
                //    }
                //    else
                //    {
                //        listBox1.Items.Add(String.Format("{0} {1} HTML文档下载成功！", i + 1, td_a.InnerText));
                //    }
                //}
                //else
                //{
                //    listBox1.Items.Add(String.Format("{0} {1} DOC文档下载成功！", i + 1, td_a.InnerText));
                //}
                //listBox1.SelectedItem = listBox1.Items[listBox1.Items.Count - 1];
                //Application.DoEvents();
            }
            #endregion
            */
        }

        private void ShowDataList(List<ZFCGObjClass> ListInfo)
        {
            foreach (ZFCGObjClass iZFCGObj in ListInfo)
            {
                object[] idatas = new object[5];
                idatas[0] = 0;
                idatas[1] = iZFCGObj.title;
                idatas[2] = iZFCGObj.datetime;
                idatas[3] = iZFCGObj.area;
                idatas[4] = iZFCGObj.url;

                dtab_ZFCG.Rows.Add(idatas);
            }
        }

        private Boolean DownloadFile(String url, String filepath)
        {
            try
            {
                if (File.Exists(filepath))
                {
                    return true;
                }
                aWebClient.DownloadFile(url, filepath);
            }
            catch
            {
                return false;
            }

            return true;
        }

        private void btn_Start_Click(object sender, EventArgs e)
        {
            if (aIsStartAnalyze)
            {
                aIsStartAnalyze = false;
                this.btn_Start.Text = "开始";
                this.txt_fasturl.Enabled = true;
                this.rbtn_auto.Enabled = true;
                this.rbtn_pagend.Enabled = true;
                this.nud_maxpage.Enabled = this.rbtn_pagend.Checked;
                this.groupBox2.Enabled = true;
            }
            else
            {
                aIsStartAnalyze = true;
                this.btn_Start.Text = "结束";
                this.txt_fasturl.Enabled = false;
                this.rbtn_auto.Enabled = false;
                this.rbtn_pagend.Enabled = false;
                this.nud_maxpage.Enabled = false;
                this.groupBox2.Enabled = false;
                this.count = 1;
                aWebBrowser.Navigate(txt_fasturl.Text);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<ZFCGObjClass> izfcgobjs = new List<ZFCGObjClass>();
            int itype = comb_type.SelectedIndex + 1;
            foreach (DataGridViewRow irow in dataGridView1.Rows)
            {
                if (irow.Cells[0].Value == null)
                {
                    continue;
                }
                if ((bool)irow.Cells[0].Value)
                {
                    ZFCGObjClass izfcgobj = new ZFCGObjClass();
                    izfcgobj.zid = 0;
                    izfcgobj.title = irow.Cells[2].Value.ToString();
                    izfcgobj.datetime = (DateTime)irow.Cells[3].Value;
                    izfcgobj.datetime_str = izfcgobj.datetime.ToString("yyyy-MM-dd");
                    izfcgobj.area = irow.Cells[4].Value.ToString();
                    izfcgobj.url = irow.Cells[6].Value.ToString();
                    izfcgobj.zid = itype;

                    izfcgobjs.Add(izfcgobj);
                }
            }
            lab_savainfo.Text = string.Format("总：{0}  当前：{1}", izfcgobjs.Count, 0);
            prob_sava.Maximum = izfcgobjs.Count;
            prob_sava.Value = 0;
            lab_savainfo.Visible = prob_sava.Visible = true;
            Updata(izfcgobjs);
            lab_savainfo.Visible = prob_sava.Visible = false;
        }

        private void Updata(List<ZFCGObjClass> datas)
        {
            string iselebasestr = "select zid from zfcg where title='{0}' and datetime='{1}'";
            string iinsertbasestr = "INSERT INTO zfcg VALUES (NULL,'{0}','{1}','{2}','{3}','{4}',{5})";
            int iindex = 0;
            int icount = datas.Count;
            foreach (ZFCGObjClass izfcgobj in datas)
            {
                prob_sava.Value = iindex++;
                lab_savainfo.Text = string.Format("总：{0}  当前：{1}", icount, iindex);
                Application.DoEvents();

                using (DbDataReader iselereader =
                    C_SqlOperate.ExecCommStr_Reader(
                    string.Format(iselebasestr, izfcgobj.title, izfcgobj.datetime_str)))
                {
                    if (iselereader.HasRows)
                    {
                        continue;
                    }
                }
                string idocpath = null;
                if (check_trydownloaddoc.Checked)
                {
                    izfcgobj.docpath = idocpath = trydownloaddoc(izfcgobj.url);
                }

                int iret = C_SqlOperate.ExecCommStr_I(string.Format(iinsertbasestr,
                    izfcgobj.title, izfcgobj.datetime_str, izfcgobj.area,
                    izfcgobj.url, izfcgobj.docpath, izfcgobj.zid), true);
            }

            MessageBox.Show("保存完成！");
        }

        private string trydownloaddoc(string url)
        {
            try
            {
                HtmlWeb iweb = new HtmlWeb();
                HtmlAgilityPack.HtmlDocument ihtmldoc = iweb.Load(url);

                HtmlNode itable = ihtmldoc.DocumentNode.SelectSingleNode("//table[@width='87%']");
                HtmlNodeCollection ias = itable.SelectNodes("//a");
                HtmlNode ianode = null;

                //优先考虑链接内容含有“招标”字眼的链接
                foreach (HtmlNode ia in ias)
                {
                    if (ia.InnerText.Contains("招标"))
                    {
                        ianode = ia;
                        break;
                    }
                }
                //如果没有则取第一个链接
                if (ianode == null)
                {
                    ianode = ias[0];
                }
                //如果所选取的链接地址为空或者不包含基本地址，则重新选取
                string ihrefvalue = ianode.Attributes["href"].Value;
                if ((ihrefvalue == null)
                    || ihrefvalue == ""
                    || (!ihrefvalue.Contains(aBaseUrl)))
                {
                    ianode = null;
                    foreach (HtmlNode ia2 in ias)
                    {
                        ihrefvalue = ia2.Attributes["href"].Value;
                        if ((ihrefvalue != "") && (ihrefvalue != null) && (ihrefvalue.Contains(aBaseUrl)))
                        {
                            ianode = ia2;
                            break;
                        }
                    }
                }

                if (ianode == null)
                {
                    return null;
                }
                string irelativelyfilepath = "\\doc\\" + ihrefvalue.Substring(ihrefvalue.LastIndexOf("/") + 1);
                string ifilepath = Application.StartupPath + irelativelyfilepath;

                if (DownloadFile(ihrefvalue, ifilepath))
                {
                    return irelativelyfilepath;
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            this.nud_maxpage.Enabled = this.rbtn_pagend.Checked;
        }

        private void rbtn_webdata_CheckedChanged(object sender, EventArgs e)
        {
            dtab_ZFCG.Clear();
            this.btn_savadata.Enabled = this.rbtn_webdata.Checked;
            this.btn_updatadoc.Enabled = !this.rbtn_webdata.Checked;
            this.btn_del.Enabled = !this.rbtn_webdata.Checked;
            this.dataGridView1.Columns[0].Visible = rbtn_webdata.Checked;
            this.dataGridView1.Columns[1].Visible = !rbtn_webdata.Checked;
        }

        private void rbtn_localhostdata_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtn_localhostdata.Checked)
            {
                dtab_ZFCG.Clear();
                int itype = comb_type.SelectedIndex + 1;
                C_SqlOperate.ExecSqlStr_FillTable(string.Format("SELECT * FROM zfcg where tid={0} ORDER BY datetime DESC LIMIT 500", itype), dtab_ZFCG);
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 5)
            {
                string ifilepath = Application.StartupPath + this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                if (File.Exists(ifilepath))
                {
                    System.Diagnostics.Process.Start(ifilepath);
                }
            }
            if (e.ColumnIndex == 6)
            {
                System.Diagnostics.Process.Start(this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            }
        }

        private void btn_updatadoc_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("请选择需要手工更新的数据行！");
                return;
            }
            if (openFileDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string isourcefilepath = openFileDialog1.FileName;
            string irelativelyfilepath = "\\doc\\" + Path.GetFileName(isourcefilepath);
            string ifilepath = Application.StartupPath + irelativelyfilepath;
            File.Copy(isourcefilepath, ifilepath, true);
            int izid = (int)dataGridView1.CurrentRow.Cells[1].Value;
            string iupdatasqlstr = "UPDATE zfcg SET docpath='{1}' WHERE zid={0}";
            int iret = C_SqlOperate.ExecCommStr_I(string.Format(iupdatasqlstr, izid, irelativelyfilepath), true);
            this.dataGridView1.CurrentRow.Cells[5].Value = ifilepath;
        }

        private void comb_type_SelectedIndexChanged(object sender, EventArgs e)
        {
            rbtn_localhostdata_CheckedChanged(null, null);
        }

        private void btn_del_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("请选择需要删除的行！");
                return;
            }

            int izid = (int)dataGridView1.CurrentRow.Cells[1].Value;
            int iret = C_SqlOperate.ExecCommStr_I(string.Format("DELETE FROM zfcg WHERE zid={0}", izid), true);
            if (iret < 0)
            {
                MessageBox.Show("删除时发生数据库错误！" + Environment.NewLine +
                    C_SqlOperate.ErrMsg);
                return;
            }
            string ifilepath = Application.StartupPath + dataGridView1.CurrentRow.Cells[5].Value.ToString();
            if (File.Exists(ifilepath))
            {
                File.Delete(ifilepath);
            }
            this.dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
        }
    }
}
